package com.castle.fortress.admin.study.course.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.core.annotation.CastleLog;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.study.course.dto.StudyCoursewareDto;
import com.castle.fortress.admin.study.course.entity.StudyCourseChapterCoursewareEntity;
import com.castle.fortress.admin.study.course.entity.StudyCoursewareEntity;
import com.castle.fortress.admin.study.course.service.StudyCourseChapterCoursewareService;
import com.castle.fortress.admin.study.course.service.StudyCoursewareService;
import com.castle.fortress.admin.utils.ExcelUtils;
import com.castle.fortress.admin.utils.PdfUtils;
import com.castle.fortress.common.entity.DynamicExcelEntity;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.enums.CoursewareTypeEnum;
import com.castle.fortress.common.enums.OperationTypeEnum;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.utils.ConvertUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 课件管理 控制器
 *
 * @author castle
 * @since 2023-01-30
 */
@Api(tags = "课件管理管理控制器")
@Controller
public class StudyCoursewareController {
    @Autowired
    private StudyCoursewareService studyCoursewareService;
    @Autowired
    private StudyCourseChapterCoursewareService studyCourseChapterCoursewareService;

    @Autowired
    private PdfUtils pdfUtils;

    /**
     * 课件管理的分页展示
     *
     * @param studyCoursewareDto 课件管理实体类
     * @param current            当前页
     * @param size               每页记录数
     * @return
     */
    @CastleLog(operLocation = "课件管理", operType = OperationTypeEnum.QUERY)
    @ApiOperation("课件管理分页展示")
    @GetMapping("/study/course/studyCourseware/page")
    @ResponseBody
    @RequiresPermissions("study:course:studyCourseware:pageList")
    public RespBody<IPage<StudyCoursewareDto>> pageStudyCourseware(StudyCoursewareDto studyCoursewareDto, @RequestParam(required = false) Integer current, @RequestParam(required = false) Integer size) {
        Integer pageIndex = current == null ? GlobalConstants.DEFAULT_PAGE_INDEX : current;
        Integer pageSize = size == null ? GlobalConstants.DEFAULT_PAGE_SIZE : size;
        Page<StudyCoursewareDto> page = new Page(pageIndex, pageSize);
        IPage<StudyCoursewareDto> pages = studyCoursewareService.pageStudyCoursewareExtends(page, studyCoursewareDto);

        return RespBody.data(pages);
    }

    /**
     * 课件管理的列表展示
     *
     * @param studyCoursewareDto 课件管理实体类
     * @return
     */
    @CastleLog(operLocation = "课件管理", operType = OperationTypeEnum.QUERY)
    @ApiOperation("课件管理列表展示")
    @GetMapping("/study/course/studyCourseware/list")
    @ResponseBody
    public RespBody<List<StudyCoursewareDto>> listStudyCourseware(StudyCoursewareDto studyCoursewareDto) {
        List<StudyCoursewareDto> list = studyCoursewareService.listStudyCourseware(studyCoursewareDto);
        return RespBody.data(list);
    }

    /**
     * 课件管理保存
     *
     * @param dto 课件管理实体类
     * @return
     */
    @CastleLog(operLocation = "课件管理", operType = OperationTypeEnum.INSERT)
    @ApiOperation("课件管理保存")
    @PostMapping("/study/course/studyCourseware/save")
    @ResponseBody
    @RequiresPermissions("study:course:studyCourseware:save")
    public RespBody<String> saveStudyCourseware(@RequestBody StudyCoursewareDto dto) {
        if (dto == null) {
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        return RespBody.data(studyCoursewareService.coursewareUrlHandle(dto));
    }

    /**
     * 课件管理编辑
     *
     * @param dto 课件管理实体类
     * @return
     */
    @CastleLog(operLocation = "课件管理", operType = OperationTypeEnum.UPDATE)
    @ApiOperation("课件管理编辑")
    @PostMapping("/study/course/studyCourseware/edit")
    @ResponseBody
    @RequiresPermissions("study:course:studyCourseware:edit")
    public RespBody<String> updateStudyCourseware(@RequestBody StudyCoursewareDto dto) {
        if (dto == null || dto.getId() == null || dto.getId().equals(0L)) {
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        return RespBody.data(studyCoursewareService.coursewareUrlHandle(dto));
    }

    /**
     * 课件管理删除
     *
     * @param id
     * @return
     */
    @CastleLog(operLocation = "课件管理", operType = OperationTypeEnum.DELETE)
    @ApiOperation("课件管理删除")
    @PostMapping("/study/course/studyCourseware/delete")
    @ResponseBody
    @RequiresPermissions("study:course:studyCourseware:delete")
    public RespBody<String> deleteStudyCourseware(@RequestParam Long id) {
        if (id == null) {
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        List<StudyCourseChapterCoursewareEntity> coursewareEntities = studyCourseChapterCoursewareService.findByCoursewareId(id);
        if (coursewareEntities != null && coursewareEntities.size() > 0) {
            return RespBody.fail("该课件已经绑定了课程，不允许被删除");
        }
        if (studyCoursewareService.removeById(id)) {
            //删除绑定关系
            studyCourseChapterCoursewareService.delByCoursewareId(id);
            return RespBody.data("保存成功");
        } else {
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }


    /**
     * 课件管理批量删除
     *
     * @param ids
     * @return
     */
    @CastleLog(operLocation = "课件管理", operType = OperationTypeEnum.DELETE)
    @ApiOperation("课件管理批量删除")
    @PostMapping("/study/course/studyCourseware/deleteBatch")
    @ResponseBody
    @RequiresPermissions("study:course:studyCourseware:deleteBatch")
    public RespBody<String> deleteStudyCoursewareBatch(@RequestBody List<Long> ids) {
        if (ids == null || ids.size() < 1) {
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        ArrayList<Long> deleteIds = new ArrayList<>(ids);
        ArrayList<Long> existIds = new ArrayList<>();
        List<StudyCourseChapterCoursewareEntity> coursewareEntities = studyCourseChapterCoursewareService.findByCoursewareIds(ids);
        for (StudyCourseChapterCoursewareEntity coursewareEntity : coursewareEntities) {
            Long coursewareId = coursewareEntity.getCoursewareId();
            if (ids.contains(coursewareId)) {
                deleteIds.remove(coursewareId);
                existIds.add(coursewareId);
            }
        }
        List<String> coursewareNameList = null;
        if (existIds.size() > 0) {
            coursewareNameList = studyCoursewareService.findByCoursewareIds(existIds);
        }
        if (deleteIds.size() < 1) {
            if (coursewareNameList != null && coursewareNameList.size() > 0) {
                return RespBody.fail("有【" + StrUtil.join(",", coursewareNameList) + "】綁定了课程，不允许被删除");
            }
        }
        if (studyCoursewareService.removeByIds(deleteIds)) {
            //删除绑定关系
            studyCourseChapterCoursewareService.delByCoursewareIds(deleteIds);
            if (coursewareNameList != null && coursewareNameList.size() > 0) {
                return RespBody.fail("有【" + StrUtil.join(",", coursewareNameList) + "】綁定了课程，不允许被删除");
            }
            return RespBody.data("保存成功");
        } else {
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 课件管理详情
     *
     * @param id 课件管理id
     * @return
     */
    @CastleLog(operLocation = "课件管理", operType = OperationTypeEnum.QUERY)
    @ApiOperation("课件管理详情")
    @GetMapping("/study/course/studyCourseware/info")
    @ResponseBody
    @RequiresPermissions("study:course:studyCourseware:info")
    public RespBody<StudyCoursewareDto> infoStudyCourseware(@RequestParam Long id) {
        if (id == null) {
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        StudyCoursewareDto studyCoursewareDto = studyCoursewareService.getByIdExtends(id);
        return RespBody.data(studyCoursewareDto);
    }

    /**
     * 动态表头导出 依据展示的字段导出对应报表
     *
     * @param dynamicExcelEntity
     * @param response
     * @throws Exception
     */
    @CastleLog(operLocation = "课件管理", operType = OperationTypeEnum.EXPORT)
    @PostMapping("/study/course/studyCourseware/exportDynamic")
    @ApiOperation("动态表头导出，依据展示的字段导出对应报表")
    public void exportDynamic(@RequestBody DynamicExcelEntity<StudyCoursewareDto> dynamicExcelEntity, HttpServletResponse response) throws Exception {
        List<StudyCoursewareDto> list = studyCoursewareService.listStudyCourseware(dynamicExcelEntity.getDto());
        //字典、枚举、接口、json常量等转义后的列表数据 根据实际情况初始化该对象，null为list数据直接导出
        List<List<Object>> dataList = null;
        /**
         * 根据实际情况初始化dataList,可参照 com.castle.fortress.admin.system.controller.TmpDemoController类中方法：exportDynamic
         */
        ExcelUtils.exportDynamic(response, dynamicExcelEntity.getFileName() + ".xlsx", null, list, dynamicExcelEntity.getHeaderList(), dataList);
    }


    /**
     * 测试接口
     *
     * @return
     */
    @ApiOperation("测试接口")
    @GetMapping("/study/course/studyCourseware/test")
    @ResponseBody
    public RespBody test() {
        String url = "https://hcses-1251334741.cos.ap-nanjing.myqcloud.com/v2test/20230710/1688961700308.pdf";
//		pdfUtils.pdf2Image(url , "C:\\Users\\86159\\Desktop\\test",96,new StudyCoursewareEntity());
        return RespBody.success("操作成功");
    }

}
